package cn.itcast.netty.c2;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.logging.LoggingHandler;

public class HelloServerOne {
    public static void main(String[] args) throws InterruptedException {
        // 创建两个 EventLoopGroup：一个用于接受新的连接，一个用于处理网络IO
//        EventLoopGroup bossGroup = new NioEventLoopGroup(1); // 主线程组
        EventLoopGroup workerGroup = new NioEventLoopGroup(); // 工作线程组

        try {
            // 创建 ServerBootstrap 对象
            ChannelFuture  bindFuture = new ServerBootstrap().group(workerGroup) // 设置 EventLoopGroup
                    .channel(NioServerSocketChannel.class) // 使用 NioServerSocketChannel 作为服务器的通道实现
                    .childHandler(new ChannelInitializer<SocketChannel>() { // 设置 ChannelInitializer
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            // 添加具体的处理器到 pipeline 中
                            ch.pipeline().addLast(new LoggingHandler());
                            ch.pipeline().addLast(new StringDecoder()); // 将 ByteBuf 转换为字符串
                            ch.pipeline().addLast(new ChannelInboundHandlerAdapter() { // 自定义 handler
                                @Override // 读事件
                                public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                                    System.out.println(msg); // 打印上一步转换好的字符串
                                }
                            });
                        }
                    }).bind(8080).sync();

            // 获取 ServerSocketChannel 的 Channel
            Channel channel = bindFuture.channel();
            // 等待 ServerSocketChannel 关闭
            channel.closeFuture().sync();

        } finally {
            // 优雅地关闭 EventLoopGroup，释放所有的资源
            workerGroup.shutdownGracefully();
        }
    }
}
